package com.qst.survey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qst.survey.mapper.AdminMapper;
import com.qst.survey.entity.Admin;
import com.qst.survey.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Date: 2021/3/19 20:43
 * @Description: 管理员服务具体实现类
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    /**
     * @param admin:
     * @return void
     * @description: TODO 管理员登录方法
     * @date 19:02:45 2021/3/17
     */
    @Transactional
    @Override
    public Admin loginAdmin(Admin admin) {
        //更具登录名字获取管理员信息
        Admin admin1 = new Admin();
        admin1.setUsername(admin.getUsername());
        //查询数据库
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", admin.getUsername());
        Admin adminResult = adminMapper.selectOne(queryWrapper);
        //对密码进行校验
        if (adminResult == null) {
            return adminResult;
        } else {
            boolean checkpw = BCrypt.checkpw(admin.getPassword(), adminResult.getPassword());
            if (checkpw) {
                return adminResult;
            } else {
                return null;
            }
        }

    }

    /**
     * @param admin:
     * @return void
     * @description: TODO 添加管理员
     * @date 13:55:25 2021/3/17
     */
    @Transactional
    @Override
    public void addAdmin(Admin admin) {
        //获取盐
        String gensalt = BCrypt.gensalt();
        //对用户密码加密
        String hashpw = BCrypt.hashpw(admin.getPassword(), gensalt);
        admin.setPassword(hashpw);
        //保存到数据库
        adminMapper.insert(admin);
        admin.getPassword();
    }

}
